using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;

public class ManagerPreloadingSectors : MonoBehaviour
{
	public delegate void OnLoaded();

	public static ManagerPreloadingSectors thisScript;

	public List<PreloadSceneSettings> scenesList = new List<PreloadSceneSettings>();

	public bool isLoading;

	public bool isStopLoading;

	public bool isUnload;

	public string nameAssetsForLoad = string.Empty;

	public SectorInfo loadSector;

	public SectorInfo lastloadSector;

	public bool sectorsIsPreloading = true;

	public bool isFirstLoading;

	public Dictionary<int, List<PreloadSector>> dictionaryPreloadSectors = new Dictionary<int, List<PreloadSector>>();

	public List<SectorCreate> listCreateSectors = new List<SectorCreate>();

	public List<SectorCreate> listFirstLoadingSectors = new List<SectorCreate>();

	public List<SectorInfo> listFirst = new List<SectorInfo>();

	public SectorStack<SectorInfo>[] stackNeedLoadSectors = new SectorStack<SectorInfo>[10];

	public bool needUnloadSectors;

	public bool SectorWithoutPreload;

	public Vector2 posPlayerV2 = Vector2.zero;

	private float timeDelayFirstLoading = 1f;

	private GameObject objPlayer;

	public Action GameStartedHandler;

	private float delayUnload = 2f;

	public Transform parentSectorPrefabs;

	private bool sceneLoaded;

	private AsyncOperation ao;

	private int _cGroundSectorIndex;

	private int _cPreloadLargeSectorIndex;

	private int _cPreloadLowSectorIndex;

	public bool sectorsLoaded;

	private bool waitIsRunning;

	private void Awake()
	{
		for (int i = 0; i < stackNeedLoadSectors.Length; i++)
		{
			stackNeedLoadSectors[i] = new SectorStack<SectorInfo>();
		}
		thisScript = this;
		isFirstLoading = true;
		if (Device.isWeakDevice)
		{
			delayUnload = 2f;
		}
		else
		{
			delayUnload = 4f;
		}
		dictionaryPreloadSectors.Add(0, new List<PreloadSector>());
		dictionaryPreloadSectors.Add(1, new List<PreloadSector>());
		dictionaryPreloadSectors.Add(2, new List<PreloadSector>());
	}

	private void Start()
	{
		if (settings.learningCompleted)
		{
			MessageWindow.instance.SetVisiblePanelLoading(true, "zatichka");
		}
	}

	public void StartCheck()
	{
		isFirstLoading = true;
		if (!SceneManager.GetActiveScene().name.Equals("Level1") && !SceneManager.GetActiveScene().name.Equals("Level1_Offline") && SceneManager.GetActiveScene().name != "Level1_LOW")
		{
			GameController.instance.hideAllPanels();
			base.enabled = false;
			StartCoroutine(WaitPolShishki());
			OnCompleteFirstLoading();
		}
		else
		{
			StartCoroutine(CheckNearestScenes());
		}
	}

	public IEnumerator CheckNearestScenes()
	{
		sceneLoaded = true;
		while (true)
		{
			foreach (PreloadSceneSettings element in scenesList)
			{
				if (!element.loaded && posPlayerV2 != Vector2.zero && Vector2.Distance(posPlayerV2, element.centerPoint) <= element.radius + 50f)
				{
					SceneManager.LoadSceneAsync(element.sceneName, LoadSceneMode.Additive);
					element.loaded = true;
				}
			}
			yield return null;
		}
	}

	private IEnumerator WaitForSceneLoaded()
	{
		if (ao != null)
		{
			while (!ao.isDone)
			{
				yield return null;
			}
		}
		sceneLoaded = true;
		yield return null;
	}

	private void Update()
	{
		if (timeDelayFirstLoading > 0f)
		{
			timeDelayFirstLoading -= Time.deltaTime;
		}
		else if (isFirstLoading)
		{
			proveritStatusLoading();
		}
		if (GameController.instance.myPlayer == null || !ActivityIndicator.canClear)
		{
			return;
		}
		if (GameController.instance.tpsCamera != null)
		{
			Vector3 vector = GameController.instance.tpsCamera.transform.position + GameController.instance.tpsCamera.transform.forward * 10f;
			posPlayerV2.x = vector.x;
			posPlayerV2.y = vector.z;
		}
		if (dictionaryPreloadSectors[0].Count > 0)
		{
			int num = 0;
			while (num < dictionaryPreloadSectors[0].Count)
			{
				if (_cGroundSectorIndex > dictionaryPreloadSectors[0].Count - 1)
				{
					_cGroundSectorIndex = 0;
				}
				if ((bool)dictionaryPreloadSectors[0][_cGroundSectorIndex])
				{
					dictionaryPreloadSectors[0][_cGroundSectorIndex].UpdateState(posPlayerV2);
				}
				num++;
				_cGroundSectorIndex++;
			}
		}
		if (dictionaryPreloadSectors[1].Count > 0)
		{
			int num2 = 0;
			while (num2 < 5)
			{
				if (_cPreloadLargeSectorIndex > dictionaryPreloadSectors[1].Count - 1)
				{
					_cPreloadLargeSectorIndex = 0;
				}
				if ((bool)dictionaryPreloadSectors[1][_cPreloadLargeSectorIndex])
				{
					dictionaryPreloadSectors[1][_cPreloadLargeSectorIndex].UpdateState(posPlayerV2);
				}
				num2++;
				_cPreloadLargeSectorIndex++;
			}
		}
		if (dictionaryPreloadSectors[2].Count <= 0)
		{
			return;
		}
		int num3 = 0;
		while (num3 < 5)
		{
			if (_cPreloadLowSectorIndex > dictionaryPreloadSectors[2].Count - 1)
			{
				_cPreloadLowSectorIndex = 0;
			}
			if ((bool)dictionaryPreloadSectors[2][_cPreloadLowSectorIndex])
			{
				dictionaryPreloadSectors[2][_cPreloadLowSectorIndex].UpdateState(posPlayerV2);
			}
			num3++;
			_cPreloadLowSectorIndex++;
		}
	}

	public IEnumerator LoadSectorsNearPoint(Vector2 spawnPos, Action onLoaded = null)
	{
		sectorsLoaded = false;
		List<SectorCreate> sectors = new List<SectorCreate>();
		for (int i = 0; i < dictionaryPreloadSectors[0].Count; i++)
		{
			if ((bool)dictionaryPreloadSectors[0][i] && dictionaryPreloadSectors[0][i].UpdateState(spawnPos))
			{
				sectors.Add(dictionaryPreloadSectors[0][i].scriptSector);
			}
		}
		for (int k = 0; k < dictionaryPreloadSectors[1].Count; k++)
		{
			if ((bool)dictionaryPreloadSectors[1][k] && dictionaryPreloadSectors[1][k].UpdateState(spawnPos))
			{
				sectors.Add(dictionaryPreloadSectors[1][k].scriptSector);
			}
		}
		for (int j = 0; j < dictionaryPreloadSectors[2].Count; j++)
		{
			if ((bool)dictionaryPreloadSectors[2][j] && dictionaryPreloadSectors[2][j].UpdateState(spawnPos))
			{
				sectors.Add(dictionaryPreloadSectors[2][j].scriptSector);
			}
		}
		BCWDebug.LogError("sectors.count: " + sectors.Count, "Debug Tdm");
		float start = Time.realtimeSinceStartup;
		while (sectors.Any((SectorCreate x) => !x.resourcesLoaded) && Time.realtimeSinceStartup < start + 7f)
		{
			BCWDebug.LogError("LoadSectors", "Debug Tdm");
			yield return null;
		}
		sectorsLoaded = true;
		if (onLoaded != null)
		{
			onLoaded();
		}
	}

	public IEnumerator LoadGroundNearPoint(Vector2 spawnPos)
	{
		List<SectorCreate> sectors = new List<SectorCreate>();
		for (int i = 0; i < dictionaryPreloadSectors[0].Count; i++)
		{
			if ((bool)dictionaryPreloadSectors[0][i] && dictionaryPreloadSectors[0][i].UpdateState(spawnPos))
			{
				sectors.Add(dictionaryPreloadSectors[0][i].scriptSector);
			}
		}
		float start = Time.realtimeSinceStartup;
		while (sectors.Any((SectorCreate x) => !x.resourcesLoaded) && Time.realtimeSinceStartup < start + 7f)
		{
			yield return null;
		}
	}

	public void SectorEndLoading(SectorCreate curSect)
	{
		PreloadSector preloadSector = null;
		for (int i = 0; i < dictionaryPreloadSectors[0].Count; i++)
		{
			if (dictionaryPreloadSectors[0][i].name.Equals(curSect.name))
			{
				preloadSector = dictionaryPreloadSectors[0][i];
				break;
			}
		}
		for (int j = 0; j < dictionaryPreloadSectors[1].Count; j++)
		{
			if (dictionaryPreloadSectors[1][j].name.Equals(curSect.name))
			{
				preloadSector = dictionaryPreloadSectors[1][j];
				break;
			}
		}
		for (int k = 0; k < dictionaryPreloadSectors[2].Count; k++)
		{
			if (dictionaryPreloadSectors[2][k].name.Equals(curSect.name))
			{
				preloadSector = dictionaryPreloadSectors[2][k];
				break;
			}
		}
		if (preloadSector != null)
		{
			preloadSector.curStatus = statusSector.load;
			preloadSector.isForceLoadSector = false;
			preloadSector.objSector = curSect.gameObject;
			preloadSector.scriptSector = curSect;
			isLoading = false;
		}
		proveritStatusLoading();
	}

	public void proveritStatusLoading()
	{
		bool flag = true;
		SectorStack<SectorInfo>[] array = stackNeedLoadSectors;
		foreach (SectorStack<SectorInfo> sectorStack in array)
		{
			if (sectorStack.Count > 0)
			{
				flag = false;
			}
		}
		if (listFirstLoadingSectors.Count == 0 && flag && sceneLoaded)
		{
			sectorsIsPreloading = false;
			if (timeDelayFirstLoading < 0f && isFirstLoading && !waitIsRunning)
			{
				waitIsRunning = true;
				StartCoroutine(WaitPolShishki());
			}
		}
		else
		{
			sectorsIsPreloading = true;
		}
	}

	private IEnumerator WaitPolShishki()
	{
		while (GameController.instance.myPlayer == null)
		{
			yield return null;
		}
		Vector3 playerPosition = GameController.instance.myPlayer.transform.position;
		yield return StartCoroutine(LoadSectorsNearPoint(new Vector2(playerPosition.x, playerPosition.z), delegate
		{
			BCWDebug.Log("Loading sector's meshes...");
		}));
		if (settings.offlineMode)
		{
			bool loadAsyncScene = true;
			if (IOSInternetConnection.isEnable && GameController.instance != null && GameController.instance.curTypeGame != 0)
			{
				loadAsyncScene = false;
			}
			if (loadAsyncScene && !SceneManager.GetActiveScene().name.Equals("Tutorial"))
			{
				yield return SceneManager.LoadSceneAsync("Level1_OfflineAdditive", LoadSceneMode.Additive);
			}
		}
		if (Device.indexWeakDevice == 0 && Application.loadedLevelName.Equals("Level1"))
		{
			yield return new WaitForSeconds(3f);
			yield return SceneManager.LoadSceneAsync("Lods_Level_1", LoadSceneMode.Additive);
		}
		yield return new WaitForSeconds(3f);
		waitIsRunning = false;
		if (GameController.instance.curTypeGame != TypeGame.race)
		{
			OnCompleteFirstLoading();
		}
	}

	private void OnCompleteFirstLoading()
	{
		ActivityIndicator.activEnabled = false;
		if (TDMController.isTeamGameType || GameController.instance.curTypeGame == TypeGame.race || GameController.instance.curTypeGame == TypeGame.TitanfallV2)
		{
			GameController.instance.hideAllPanels();
			GameInfoWindow.instance.ShowStartGameWindow();
			StartCoroutine(HideLoading());
		}
		else
		{
			GameController.instance.showWindowGame();
		}
		MapWindow.ResetBoundsMap();
		if (!settings.offlineMode && settings.learningCompleted)
		{
			PhotonNetwork.isMessageQueueRunning = true;
		}
		isFirstLoading = false;
		if (settings.offlineMode && MobSpawnController.instance != null)
		{
			MobSpawnController.instance.enabled = true;
		}
		else if (PhotonNetwork.isMasterClient)
		{
			controllerConnectGame.thisScript.ActivateRoomAfterDelay();
		}
		else
		{
			PVPManager.instance.ReadyToTakeInfo();
		}
		if (GameStartedHandler != null)
		{
			GameStartedHandler();
		}
	}

	private IEnumerator HideLoading()
	{
		yield return null;
		yield return null;
		yield return null;
		MessageWindow.instance.panelLoading.SetActive(false);
	}

	private void OnDestroy()
	{
		isLoading = false;
		isStopLoading = false;
		thisScript = null;
	}
}
